#include "qobjectproperty.h"

#include "qobjectmanager.h"
#include "qproperty.h"

#include <QStringList>

QObjectProperty::QObjectProperty(QObjectManager *manager, QObject *object, QObject *parent):
    QObject(parent),
    m_manager(manager),
    m_object(object)
{
    m_groups=object->property("designer_all_groups").toStringList();

    QString group;
    QProperty *pro;
    QString  name;
    QString className;
    className=object->property("className").toString();
    if(className=="")
    {
        className=object->metaObject()->className();
    }
    PropertyList plist;
    for(int i=0;i<m_groups.size();i++)
    {
        group=m_groups.at(i);
        QStringList pros=object->property(QString("designer_"+group).toLocal8Bit()).toStringList();
        for(int j=0;j<pros.size();j++)
        {
            name=pros.at(j);
            pro=createProperty(name,className);
            if(pro!=NULL)
            {
                plist.append(pro);
                m_propertys.append(pro);
                pro->setObject(object);
                connect(pro,SIGNAL(changed()),this,SLOT(propertyChanged()));
                m_nameToPropertys.insert(name,pro);
                QList<QProperty*> list=pro->children();
                pro->setGroup(group);
                while(list.size()>0)
                {
                    QProperty *child=list.first();
                    child->setObject(object);
                    m_propertys.append(child);
                    child->setGroup(group);
                    connect(child,SIGNAL(changed()),this,SLOT(propertyChanged()));
                    child->setReset(false);
                    m_nameToPropertys.insert(child->name(),child);
                    list.removeFirst();
                    list+=child->children();
                }
                pro->setValue(object->property(name.toLocal8Bit()));
            }
        }
    }

    connect(this,SIGNAL(updatePropertyAttribute()),m_object,SLOT(updatePropertyAttribute()));

    QVariant v;
    v.setValue<PropertyList>(plist);
    m_object->setProperty("property_list",v);
    emit updatePropertyAttribute();
}

QList<QProperty*> QObjectProperty::propertys()
{
    return m_propertys;
}

QStringList QObjectProperty::groups()
{
    return m_groups;
}

QProperty* QObjectProperty::createProperty(const QString &name, const QString &className)
{
    return m_manager->createProperty(name,className);
}

void QObjectProperty::propertyChanged()
{
    emit changed((QProperty*)sender());
}

QObject* QObjectProperty::object()
{
    return m_object;
}

QProperty* QObjectProperty::getProperty(const QString &name)
{
    return m_nameToPropertys.value(name);
}

void QObjectProperty::updateDefaultValue()
{
    foreach(QProperty *p,m_propertys)
    {
        p->setDefaultValue(p->value());
    }
}
